package com.cruzr.opengles.map;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.cruzr.opengles.R;

import java.io.InputStream;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

public class GLMapActivity extends AppCompatActivity {

    private static final String TAG = "GLMapActivity";

    private GLMapView mMapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_gl_map_edit);
        mMapView = findViewById(R.id.gl_map_view);

        Observable.create(obj -> {
            initData();
        }).subscribeOn(Schedulers.io()).subscribe();
    }

    private void initData() {
        byte[] bytes = readFromAssets("map/map.data");
        if (bytes == null || bytes.length == 0) {
            return;
        }
        Log.i(TAG, "initData -> bytes.length : " + bytes.length);
        byte[] wByte = new byte[4];
        byte[] hByte = new byte[4];
        byte[] pixels = new byte[bytes.length - 8];
        System.arraycopy(bytes, 0, wByte, 0, 4);
        System.arraycopy(bytes, 4, hByte, 0, 4);
        System.arraycopy(bytes, 8, pixels, 0, bytes.length - 8);
        int width = byteArrayToInt(wByte);
        int height = byteArrayToInt(hByte);
        Log.i(TAG, "initData -> width : " + width + ", height : " + height);

        mMapView.loadMap(width, height, pixels);
    }

    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (3 - i) * 8;
            value += (bytes[i] & 0xFF) << shift;
        }
        return value;
    }

    public byte[] readFromAssets(String fileName) {
        byte[] buffer = null;
        AssetManager am = getAssets();
        try {
            InputStream inputStream = am.open(fileName);
            int length = inputStream.available();
            buffer = new byte[length];
            inputStream.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        super.onDestroy();
    }

}
